<?php
namespace Home\Controller;

class UserController extends ParentController {
    protected function _initialize() {
        $this->hasRight = parent::isLogin();
    }

    /**
     * 获取用户个人信息
     * @modify trainyao 2016-05-09    创建
     */
    public function info() {
        if (empty($this->hasRight)) {
            returnJson(403, 304);
            return;
        }
        $hotelId = I('post.hotel');
        $areaCode = session(C('USER_AREACODE'));
        $mobile = session(C('USER_MOBILE'));
        $vipUserModel = D('VipUser');
        $vipUserInfo = $vipUserModel->getInfoByMobile($hotelId, $mobile, $areaCode);
        $vipInfoModel = D('VipInfo');
        $vipInfo = $vipInfoModel->getInfoById($vipUserInfo['vipinfo_id']);

        $userLoginModel = D('UserLogin');
        $userLoginInfo = $userLoginModel->getInfoByMobile($mobile, $areaCode);
        // 调用RPC 获取对应的身份证信息
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('QRCLIENTSYNC_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'webUserId' => $userLoginInfo['id'],
            'areaCode' => $areaCode,
            'mobile' => $mobile,
            'isSync' => false,
        );
        // 微信登录且未绑定手机号的 不需要请求
        if (!is_null($mobile) && !is_null($areaCode)) {
            $qrclientDate = $client->getPersonInfo($RPCData);
        }

        $returnData = array(
            'name' => session(C('USER_NAME')),
            'areaCode' => isset($areaCode) ? $areaCode : '86',
            'mobile' => $mobile,
            'authLogin' => 0,
            'bindMobile' => 0,
            'vipInfo' => $vipInfo,
            'identity' => !empty($qrclientDate['ididentity']) ? $qrclientDate['ididentity'] : '',
            'idname' => !empty($qrclientDate['idname']) ? $qrclientDate['idname'] : '',
            'idsex' => !empty($qrclientDate['idsex']) ? $qrclientDate['idsex'] : '',
            'idnation' => !empty($qrclientDate['idnation']) ? $qrclientDate['idnation'] : '',
            'idaddress' => !empty($qrclientDate['idaddress']) ? $qrclientDate['idaddress'] : '',
        );
        $authLoginType = session(C('AUTH_LOGIN_TYPE'));
        if (!is_null($authLoginType)) {
            $returnData['authLogin'] = $authLoginType;
            $returnData['bindMobile'] = empty($returnData['mobile']) ? 0 : 1;
        }
        returnJson(200, 200, $returnData);
    }

    /**
     * 获取用户会员信息
     * @modify zhangzhen 2017-03-13    创建
     */
    public function getVipInfo() {
        $hotelId = I('post.hotel');
        $mobile = I('post.mobile');
        $areaCode = I('post.areaCode', '86', 'string');
        $vipUserModel = D('VipUser');
        $vipUserInfo = $vipUserModel->getInfoByMobile($hotelId, $mobile, $areaCode);
        $vipInfoModel = D('VipInfo');
        $vipInfo = $vipInfoModel->getInfoById($vipUserInfo['vipinfo_id']);
        returnJson(200, 200, $vipInfo);
    }

    /**
     * @description  获取身份证图片数据
     * @modify wenhui 2016-06-19
     */
    public function getIdInformation() {

        $param = I('post.');

        // web端压缩过的base64图片格式 去掉 开头的 image/jpeg;base64, substr($param['baseface'], 23)
        $baseface = isset($param['baseface']) ? substr($param['baseface'], 23) : null;
        $baseback = isset($param['baseback']) ? substr($param['baseback'], 23) : null;

        if (is_null($baseface) && isset($baseback)) {
            // 表单上传图片
            $config_info = C('identity');
            // 检测文件大小
            if ($_FILES['face']['size'] === 0) {
                returnJson(403, 600);
                return;
            }

            $fileSizes = array_column($_FILES, 'size');
            foreach ($fileSizes as $fileSize) {
                if ($fileSize > $config_info['maxSize']) {
                    returnJson(403, 600);
                    return;
                }
            }
            unset($fileSize);

            $config = array(
                'maxSize' => $config_info['maxSize'],
                'rootPath' => $config_info['rootPath'],
                'savePath' => $config_info['savePath'],
                'exts' => $config_info['exts'],
                'subName' => array('date', 'Ymd'),
            );

            $upload = new \Think\Upload($config);
            $info = $upload->upload();
            if (!$info) {
                returnJson(500, 506, $upload->getError());
                return;
            }
            if (isset($info['face'])) {
                $fileNameData['face'] = 'Uploads/' . $info['face']['savepath'] . $info['face']['savename'];  
            }
            if (isset($info['back'])) {
                $fileNameData['back'] = 'Uploads/' . $info['back']['savepath'] . $info['back']['savename'];  
            }

            if (!isset($fileNameData) || empty($fileNameData)  || !isset($fileNameData['face'])) {
                returnJson(500, 506);
                return;
            }
            // 获取图片数据
            $jsonData = getIdDate($fileNameData);
            if ($jsonData == false) {
                // 删除图片
                foreach ($fileNameData as $key => $fileName) {
                    unlink($fileName);
                }
                returnJson(500, 506);
                return;
            }

            // 删除图片
            foreach ($fileNameData as $key => $fileName) {
                unlink($fileName);
            }
        } else {
            // face 必填
            if (is_null($baseface)) {
                returnJson(500, 506);
                return;
            }
            // 获取图片数据
            $jsonData = getIdDate(array('baseface' => $baseface, 'baseback' => $baseback));
        }

        // 组装数据
        $imageData = array();
        foreach ($jsonData['outputs'] as $key => $value) {
            $valueDate = json_decode($value['outputValue']['dataValue'], true);
            $config_str = json_decode($valueDate['config_str'], true);
            if ($config_str['side'] == 'face') {
                $imageData['name'] = $valueDate['name'];
                $imageData['sex'] = $valueDate['sex'];
                $imageData['nationality'] = $valueDate['nationality'];
                $imageData['num'] = $valueDate['num'];
                $imageData['address'] = $valueDate['address'];
            } else {
                $imageData['issue'] = $valueDate['issue'];
                $imageData['start_date'] = $valueDate['start_date'];
                $imageData['end_date'] = $valueDate['end_date'];
            }
        }

        if (empty($imageData) || empty($imageData['name'])) {
            returnJson(500, 506);
            return;
        }

        returnJson(200, 200, $imageData);
    }

     /**
     * @description  保存绑定数据
     * @modify wenhui 2016-06-19
     */
    public function saveInformation() {
        if (empty($this->hasRight)) {
            returnJson(403, 304);
            return;
        }
        $param = I('post.');
        $validateRule = array(
            'idName' => 'notnull,notempty',
            'idSex' => 'notnull,notempty',
            'idNation' => 'notnull,notempty',
            'idIdentity' => 'notnull,notempty,IDCard',
            'idAddress' => 'notnull,notempty',
        );
        try {
            \Org\Util\Validate::validate($param, $validateRule);
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }

        $areaCode = session(C('USER_AREACODE'));
        $mobile = session(C('USER_MOBILE'));
        $userLoginModel = D('UserLogin');
        // 检查用户是否存在
        $userLoginInfo = $userLoginModel->getInfoByMobile($mobile, $areaCode);
        if (empty($userLoginInfo)) {
            returnJson(403, 300);
            return;
        }

        $idName = isset($param['idName']) ? $param['idName'] : null;
        $idSex = isset($param['idSex']) ? $param['idSex'] : null;
        $idNation = isset($param['idNation']) ? $param['idNation'] : null;
        $idIdentity = isset($param['idIdentity']) ? $param['idIdentity'] : null;
        $idAddress = isset($param['idAddress']) ? $param['idAddress'] : null;

        // 调用RPC 保存绑定身份证信息
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('QRCLIENTSYNC_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'webUserId' => $userLoginInfo['id'],
            'areaCode' => $areaCode,
            'mobile' => $mobile,
            'idName' => $idName,
            'idSex' => $idSex,
            'idNation' => $idNation,
            'idIdentity' => $idIdentity,
            'idAddress' => $idAddress,
        );
        $saveResult = $client->saveInformation($RPCData);
        if (isset($saveResult['status']) && $saveResult['status'] == 201) {
            returnJson(403, 305);
            return;
        }
        if ($saveResult == false) {
            returnJson(403, 305);
            return;
        }

        returnJson(200, 200, 'success');
    }

    /**
     * @description  获取身份证数据
     * @modify wenhui 2016-06-19
     */
    public function getPersonIdInfo() {
        if (empty($this->hasRight)) {
            returnJson(403, 304);
            return;
        }

        // 微信登录并且未绑定手机号  不需要获取身份证数据
        $wechatAndNotBindMobile = session(C('AUTH_LOGIN_TYPE')) == USER_OAUTH_TYPE_WECHAT_WEB && empty(session(C('USER_MOBILE')));
        if ($wechatAndNotBindMobile) {
            returnJson(200, 200, array('WechatAndBind' => true, 'isBind' => false));
        } else {
            $param = I('post.');

            $areaCode = isset($param['areaCode']) ? $param['areaCode'] : session(C('USER_AREACODE'));
            $mobile = isset($param['mobile']) ? $param['mobile'] : session(C('USER_MOBILE'));
            $userLoginModel = D('UserLogin');
            $userLoginInfo = $userLoginModel->getInfoByMobile($mobile, $areaCode);
            if (empty($userLoginInfo)) {
                returnJson(403, 300);
                return;
            }

            // 调用RPC 获取对应的身份证信息
            Vendor('phpRPC.phprpc_client');
            $client = new \PHPRPC_Client(C('QRCLIENTSYNC_RPC_URL'));
            $client->setEncryptMode(3);
            $RPCData = array(
                'flag' => C('MEIZHU_RPC_FLAG'),
                'time' => time(),
                'webUserId' => $userLoginInfo['id'],
                'areaCode' => $areaCode,
                'mobile' => $mobile,
            );
            $qrclientDate = $client->getPersonInfo($RPCData);
            if ($qrclientDate == false || empty($qrclientDate['ididentity'])) {
                returnJson(200, 200, array('isBind' => false, 'WechatAndBind' => false));
                return;
            }

            // 组装数据
            unset($qrclientDate['id']);
            unset($qrclientDate['userlogin_id']);
            unset($qrclientDate['nickname']);
            unset($qrclientDate['gender']);
            unset($qrclientDate['telephone']);
            unset($qrclientDate['problemprotection_id']);
            unset($qrclientDate['answer']);
            unset($qrclientDate['identity']);
            unset($qrclientDate['name']);
            unset($qrclientDate['createtime']);
            unset($qrclientDate['updatetime']);
            $qrclientDate['isBind'] = true;
            $qrclientDate['WechatAndBind'] = false;

            returnJson(200, 200, $qrclientDate);
        }
    }

    /**
     * 检查是否微信登录,是否需要绑定,并进行处理
     * @modify wenhui 2017-07-31
     */
    public function wechatBindBook() {
        if (empty($this->hasRight)) {
            returnJson(403, 304);
            return;
        }

        $param = I('post.');
        // 微信登录并且未绑定手机号需要校验
        $wechatAndNotBindMobile = session(C('AUTH_LOGIN_TYPE')) == USER_OAUTH_TYPE_WECHAT_WEB && empty(session(C('USER_MOBILE')));
        if ($wechatAndNotBindMobile) {
            $validateRule = array(
                'hotel' => 'notnull,notempty,id',
                'vcode' => 'notnull,notempty,vcode',
                'areaCode' => 'notnull,notempty',
                'mobile' => 'notnull,notempty',
            );
            try {
                \Org\Util\Validate::validate($param, $validateRule);
                \Org\Util\Validate::validate($param['mobile'], 'globalMobile', array('globalMobile' => array('function', 'checkGlobalMobile,' . $param['areaCode'], '403,130,error')));
            } catch (\Exception $e) {
                returnJson($e->getMessage());
                return;
            }

            // 校验验证码,session是否有值,验证码是否已经过期
            $vcodeInSession = session(C('BOOK_LOGIN_VALIDATE_CODE'));
            $vcodeSendTime = session(C('BOOK_LOGIN_VALIDATE_CODE_SEND_TIME'));
            $mobileInSession = session(C('BOOK_LOGIN_MOBILE'));
            $mobile = $param['mobile'];
            if (empty($vcodeInSession) || empty($vcodeSendTime) || empty($mobileInSession) || $mobile != $mobileInSession) {
                returnJson(403, 100);
                return;
            }
            if (isOverMinute($vcodeSendTime, C('VALIDATE_CODE_OUTDATE_MINUTE'))) {
                returnJson(403, 201);
                return;
            }
            $vcode = $param['vcode'];
            if ($vcode != $vcodeInSession) {
                returnJson(403, 202);
                return;
            }
            $areaCode = isset($param['areaCode']) ? $param['areaCode'] : '86';
            $userLogic = A('Common/User', 'Logic');
            // 查询信息是否存在
            $userAuthModel = D('UserAuth');
            $userAuthInfo = $userAuthModel->getInfoByOauthType(session(C('WECHAT_LOGIN_OPEN_ID')), USER_OAUTH_TYPE_WECHAT_WEB);
            if (empty($userAuthInfo)) {
                returnJson(500, 500);
            }

            // 校验成功,进行注册并登录
            $userData = $userLogic->checkUserExist($mobile, $areaCode);
            try {
                if (empty($userData)) {
                    $name = isset($userAuthInfo['name']) ? $userAuthInfo['name'] : '';
                    $string = chr(mt_rand(97,122));
                    $password = $string . getRandomNumber(5);
                    $registerResult = $userLogic->register($mobile, $password, $name, $areaCode);
                    // 发短信
                    if ($registerResult != false) {
                        $loginLink = "http://" . MEIZHU_BOOK_HOST . "/Home/BookPage/index?hotel={$param['hotel']}";
                        $loginLink = shortenUrl($loginLink);

                        if ($areaCode == '86') {
                            $smsUtil = new \Org\Util\Sms();
                            $smsSendResult = $smsUtil->sendNotRegBook($mobile, $password, $loginLink);
                        } else {
                            $smsUtil = new \Org\Util\yunPian();
                            $smsSendResult = $smsUtil->yunPianSendNotRegBook($areaCode, $mobile, $password, $loginLink);
                        }
                    }
                    $userData = $userLogic->login($mobile, null, $areaCode);

                    // 把账号同步到钥匙包
                    $userLogic->qrclientRegister($mobile, $name, $areaCode);
                }
                // 自动登录成功,写入session
                session(C('USER_AREACODE'), $userData['areacode']);
                session(C('USER_ID'), $userData['id']);
                session(C('USER_MOBILE'), $userData['mobile']);
                session(C('USER_NAME'), $userData['name']);

                // 绑定,并进行处理
                $userLogic->bindUser($userData['id'], session(C('WECHAT_LOGIN_OPEN_ID')), USER_OAUTH_TYPE_WECHAT_WEB);

            } catch (\Exception $e) {
                returnJson($e->getMessage());
                return;
            }
            session(C('BOOK_LOGIN_VALIDATE_CODE'), null);
            session(C('BOOK_LOGIN_VALIDATE_CODE_SEND_TIME'), null);
            session(C('BOOK_LOGIN_MOBILE'), null);

            // 调用RPC 获取对应的身份证信息
            Vendor('phpRPC.phprpc_client');
            $client = new \PHPRPC_Client(C('QRCLIENTSYNC_RPC_URL'));
            $client->setEncryptMode(3);
            $RPCData = array(
                'flag' => C('MEIZHU_RPC_FLAG'),
                'time' => time(),
                'webUserId' => $userData['id'],
                'areaCode' => $areaCode,
                'mobile' => $mobile,
            );
            $qrclientDate = $client->getPersonInfo($RPCData);
            if ($qrclientDate == false || empty($qrclientDate['ididentity'])) {
                returnJson(200, 200, array('isBind' => false, 'WechatAndBind' => false));
                return;
            }

            // 组装数据
            unset($qrclientDate['id']);
            unset($qrclientDate['userlogin_id']);
            unset($qrclientDate['nickname']);
            unset($qrclientDate['gender']);
            unset($qrclientDate['telephone']);
            unset($qrclientDate['problemprotection_id']);
            unset($qrclientDate['answer']);
            unset($qrclientDate['identity']);
            unset($qrclientDate['name']);
            unset($qrclientDate['createtime']);
            unset($qrclientDate['updatetime']);
            $qrclientDate['areacode'] = $areaCode;
            $qrclientDate['mobile'] = $mobile;
            $qrclientDate['isBind'] = true;
            $qrclientDate['WechatAndBind'] = false;

            returnJson(200, 200, $qrclientDate);
        } else {
            returnJson(200, 200, array('isBind' => false, 'WechatAndBind' => false));
        }
    }

    /**
     * 发送预定登录验证码
     * @modify wenhui 2017-07-31
     */
    public function wechatBookVcode() {
        $param = I('post.');
        $areaCode = I('post.areaCode', '86', 'string');
        try {
            \Org\Util\Validate::validate($param['mobile'], 'globalMobile', array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error')));
        } catch (\Exception $e) {
            returnJson($e->getMessage());
            return;
        }

        // 发送短信验证码
        $mobile = $param['mobile'];

        // 校验1分钟内是否已经发送过
        $sendTime = session(C('BOOK_LOGIN_VALIDATE_CODE_SEND_TIME'));
        if (!empty($sendTime) && !isOverMinute($sendTime, C('VALIDATE_CODE_RESENT_MINUTE'))) {
            returnJson(403, 200);
            return;
        }

        // 生成随机数字发送
        $vcode = getRandomNumber(4);
        if ($areaCode == '86') {
            $smsUtil = new \Org\Util\Sms();
            $smsSendResult = $smsUtil->sendVocode($mobile, $vcode);
        } else {
            $smsUtil = new \Org\Util\yunPian();
            $smsSendResult = $smsUtil->sendVcode($areaCode, $mobile, $vcode);
        }

        if (empty($smsSendResult)) {
            returnJson(500, 507);
            return;
        }

        $time = time();
        session(C('BOOK_LOGIN_MOBILE'), $mobile);
        session(C('BOOK_LOGIN_VALIDATE_CODE'), $vcode);
        session(C('BOOK_LOGIN_VALIDATE_CODE_SEND_TIME'), $time);

        returnJson(200, 200);
    }
}
